package com.greendragon.persistence.dao.impl;

import java.util.List;

import org.apache.log4j.Logger;

import com.greendragon.persistence.dao.IUserDao;
import com.greendragon.persistence.domain.User;
import com.greendragon.persistence.enmu.FetchOrderType;
import com.greendragon.persistence.enmu.LockType;
import com.greendragon.persistence.enmu.UserRoleType;

/**
 * @author wulibin, exceptsky@gmail.com, 2011-9-8 下午11:25:41
 * 
 */
public class UserDaoImpl extends BaseDao<User> implements IUserDao {
	private static Logger          logger           = Logger.getLogger(UserDaoImpl.class);
	
	@Override
	@SuppressWarnings("unchecked")
	public User getByName(String name) {
		String hql = "from User u where u.name = ?";
		try {
			List rs = getHibernateTemplate().find(hql, name);
			if(rs==null || rs.size()==0){
				return null;
			}
			User result = (User)rs.listIterator().next();
			return result;
		} catch (Exception e) {
			logger.error(e);
			return null;
		}

	}
	
	@Override
	public List<User>getByRole(int offset,int length, UserRoleType roleType, LockType lockType, FetchOrderType orderType){
		String hql;
		hql = "from User as u where u.role=? and"+getLockSql("u", lockType)+getOrderSql("u", orderType);
		return selectByPage(hql, new String[]{roleType.getName()}, offset, length);
	}
	
	@Override
	public List<User> search(int offset,int length, String key){
		String hql;
		hql = "from User as u where u.name like ? or u.displayName like ?"+getOrderSql("u", FetchOrderType.CREATE_DESC);
		return selectByPage(hql, new String[]{"%"+key+"%","%"+key+"%"}, offset, length);
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public long countOfsearch(String key){
		String hql = "select count(u.id) from User as u where u.name like ? or u.displayName like ?";
		try {
			List rs = getHibernateTemplate().find(hql, new String[]{"%"+key+"%","%"+key+"%"});
			if(rs==null || rs.size()==0){
				return 0l;
			}
			long count = (Long)rs.listIterator().next();
			return count;
		} catch (Exception e) {
			logger.error(e);
			return 0l;
		}
	}
}
